/**
 *Copyright (c) 2024 watereyes
 * safetymanagement is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan
 * PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *          http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package com.koron.accident.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.koron.accident.domain.AccidentBulletin;
import com.koron.accident.mapper.AccidentBulletinMapper;
import com.koron.accident.service.api.AccidentBulletinService;
import com.koron.accident.util.BusinessCode;
import com.koron.audit.approval.AfterApprovalService;
import com.koron.audit.domain.Audit;
import com.koron.audit.management.FlowManagement;
import com.koron.common.bean.StaffBean;
import com.koron.common.dfs.FastDFSClientWrapper;
import com.koron.common.domain.DataBean;
import com.koron.common.emailandsms.SendEmail;
import com.koron.common.emailandsms.SendMsg;
import com.koron.common.generator.DefaultIdGenerator;
import com.koron.common.web.Util;
import com.koron.hazardsource.util.Immutable;
import com.koron.system.domain.DictData;
import com.koron.system.domain.Message;
import com.koron.system.mapper.MessageMapper;
import com.koron.system.service.api.DictDataService;
import org.apache.commons.lang3.StringUtils;
import org.koron.ebs.mybatis.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.swan.bean.MessageBean;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class AccidentBulletinServiceImpl implements AccidentBulletinService, AfterApprovalService, InitializingBean {

    private  final Logger logger = LoggerFactory.getLogger(AccidentBulletinServiceImpl.class);

    @Autowired
    private DictDataService dataService;

    @Autowired
    private FastDFSClientWrapper clientWrapper;

    @Autowired
    private Util util;

    @Autowired
    private FlowManagement flowManagement;

    @Value("${accident_bulletin}")
    private String accidentBulletin;

    @Override
    public MessageBean<Integer> save(StaffBean user, AccidentBulletin bean, String approver, String keepFiles, String delFiles, MultipartFile[] files) {
        MessageBean<Integer> msg = new MessageBean<>();
        List<String> keepList = new ArrayList<>();
        try (SessionFactory factory = new SessionFactory()) {
            if (StringUtils.isEmpty(bean.getName())) {
                msg.setCode(BusinessCode.ACCIDENTBULLETIN_EMPTY_NAME.getCode());
                msg.setDescription(BusinessCode.ACCIDENTBULLETIN_EMPTY_NAME.getDescription());
                return msg;
            }
            if (StringUtils.isEmpty(bean.getDepartmentCode()) || StringUtils.isEmpty(bean.getDepartmentName())) {
                msg.setCode(BusinessCode.ACCIDENTBULLETIN_EMPTY_DEPARTMENTCODE.getCode());
                msg.setDescription(BusinessCode.ACCIDENTBULLETIN_EMPTY_DEPARTMENTCODE.getDescription());
                return msg;
            }
            if (StringUtils.isEmpty(bean.getAccidentType())) {
                msg.setCode(BusinessCode.ACCIDENTBULLETIN_EMPTY_ACCIDENTTYPE.getCode());
                msg.setDescription(BusinessCode.ACCIDENTBULLETIN_EMPTY_ACCIDENTTYPE.getDescription());
                return msg;
            }
            if (StringUtils.isEmpty(approver)) {
                msg.setCode(BusinessCode.ACCIDENTBULLETIN_EMPTY_MANAGER.getCode());
                msg.setDescription(BusinessCode.ACCIDENTBULLETIN_EMPTY_MANAGER.getDescription());
                return msg;
            }
            if (null != files && files.length > 0) {
                for (MultipartFile file : files) {
                    String url = clientWrapper.uploadFile(file);
                    keepList.add(url + "#" + file.getOriginalFilename());
                }
            }
            bean.setStatus(0);
            bean.setIsRemove(0);
            Integer value = 0;
            Audit audit = new Audit();
            audit.setTitle((StringUtils.isEmpty(bean.getId()) ? "新增事故快报：" : "修改事故快报：") + bean.getName());
            if (StringUtils.isEmpty(bean.getId())) {
                //新增
                bean.setId(DefaultIdGenerator.getInstance().generateLongId());
                bean.setAddTime(bean.getUpdateTime());
                bean.setAddUser(bean.getUpdateUser());
                bean.setAddUserName(bean.getUpdateUserName());
                if (null != keepList && keepList.size() > 0)
                    bean.setAttachment(new Gson().toJson(keepList));
                value = factory.getMapper(AccidentBulletinMapper.class).insert(bean);
            } else {
                //修改
                AccidentBulletin entity = queryOne(bean.getId()).getData();
                if (null == entity) {
                    msg.setCode(BusinessCode.ACCIDENTBULLETIN_NOT_EXIST.getCode());
                    msg.setDescription(BusinessCode.ACCIDENTBULLETIN_NOT_EXIST.getDescription());
                    return msg;
                }
                if (entity.getStatus() == 0) {
                    msg.setCode(BusinessCode.ACCIDENTBULLETIN_IS_APPROVING.getCode());
                    msg.setDescription(BusinessCode.ACCIDENTBULLETIN_IS_APPROVING.getDescription());
                    return msg;
                }
                if (StringUtils.isNotEmpty(keepFiles)) {
                    String[] keepArray = keepFiles.split("[,，]");
                    keepList.addAll(Arrays.asList(keepArray).stream().map(String::trim).collect(Collectors.toList()));
                }
                if (null != keepList && keepList.size() > 0)
                    bean.setAttachment(new Gson().toJson(keepList));
                value = factory.getMapper(AccidentBulletinMapper.class).update(bean);
                if (value > 0) {
                    if (StringUtils.isNotEmpty(delFiles)) {
                        String[] delArray = delFiles.split("[,，]");
                        for (String url : delArray) {
                            clientWrapper.deleteFile(url.split("#")[0]);
                        }
                    }
                }
            }
            if (value > 0) {
                //启动流程
                //启动流程
                Date date = new Date();
                audit.setAddUser(bean.getUpdateUserName());
                audit.setAddTime(date);
                audit.setUpdateUser(bean.getUpdateUserName());
                audit.setUpdateTime(date);
                audit.setFlowType(1);
                audit.setFlowName(Immutable.ACCIDENT_BULLETIN);
                audit.setOperation(1);
                audit.setTarget(AccidentBulletinServiceImpl.class.getName());
                audit.setCorpCode(bean.getCorpCode());
                audit.setBusinessIds(bean.getId());
                audit.setInitiatorCode(bean.getUpdateUser());
                audit.setDescription(bean.getName() + "");
                audit.setState(1);
                audit.setTemplateKey(accidentBulletin);
                audit.setSetCode("institution_manage");
                audit.setInitiatorAccount(user.getUserid());
                audit.setId(DefaultIdGenerator.getInstance().generateLongId());
                Map<String, Object> businessMap = new HashMap<>();
                businessMap.put("approver", approver);
                if (!flowManagement.initFlow(user, audit, businessMap)) {
                    factory.close(false);
                    msg.setCode(BusinessCode.FAILURE.getCode());
                    msg.setDescription("提交失败，原因是无法启动流程");
                    return msg;
                }
                msg.setCode(BusinessCode.SUCCESS.getCode());
                msg.setDescription("保存成功");
                msg.setData(value);
                return msg;
            } else {
                if (null != keepList && keepList.size() > 0) {
                    if (StringUtils.isEmpty(keepFiles)) {
                        for (String url : keepList) {
                            clientWrapper.deleteFile(url.split("#")[0]);
                        }
                    } else {
                        List<String> keeps = Arrays.asList(keepFiles.split("[,，]"));
                        for (String url : keepList) {
                            if (!keeps.contains(url)) {
                                clientWrapper.deleteFile(url.split("#")[0]);
                            }
                        }
                    }
                }
                msg.setCode(BusinessCode.FAILURE.getCode());
                msg.setDescription("保存失败");
                msg.setData(value);
                return msg;
            }
        } catch (Exception e) {
            if (null != keepList && keepList.size() > 0) {
                if (StringUtils.isEmpty(keepFiles)) {
                    for (String url : keepList) {
                        clientWrapper.deleteFile(url.split("#")[0]);
                    }
                } else {
                    List<String> keeps = Arrays.asList(keepFiles.split("[,，]"));
                    for (String url : keepList) {
                        if (!keeps.contains(url)) {
                            clientWrapper.deleteFile(url.split("#")[0]);
                        }
                    }
                }
            }
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
            return msg;
        }
    }

    @Override
    public MessageBean<Integer> delete(StaffBean user, String id, String approver) {
        MessageBean<Integer> msg = new MessageBean<>();
        try (SessionFactory factory = new SessionFactory()) {
            if (StringUtils.isEmpty(id)) {
                msg.setCode(BusinessCode.EXCEPTION.getCode());
                msg.setDescription(BusinessCode.EXCEPTION.getDescription());
                return msg;
            }
            if (StringUtils.isEmpty(approver)) {
                msg.setCode(BusinessCode.ACCIDENTBULLETIN_EMPTY_MANAGER.getCode());
                msg.setDescription(BusinessCode.ACCIDENTBULLETIN_EMPTY_MANAGER.getDescription());
                return msg;
            }
            AccidentBulletin entity = queryOne(id).getData();
            if (null == entity) {
                msg.setCode(BusinessCode.ACCIDENTBULLETIN_NOT_EXIST.getCode());
                msg.setDescription(BusinessCode.ACCIDENTBULLETIN_NOT_EXIST.getDescription());
                return msg;
            }
            if (entity.getStatus() == 0) {
                msg.setCode(BusinessCode.ACCIDENTBULLETIN_IS_APPROVING.getCode());
                msg.setDescription(BusinessCode.ACCIDENTBULLETIN_IS_APPROVING.getDescription());
                return msg;
            }
            Integer status = entity.getStatus();
            if (status == 2) {
                entity.setIsRemove(1);
            } else {
                entity.setStatus(0);
            }
            Integer value = factory.getMapper(AccidentBulletinMapper.class).update(entity);
            if (value > 0) {
                if (status != 2) {
                    //启动删除事件管理流程
                    //启动流程
                    Date date = new Date();
                    Audit audit = new Audit();
                    audit.setAddUser(entity.getUpdateUserName());
                    audit.setAddTime(date);
                    audit.setUpdateUser(entity.getUpdateUserName());
                    audit.setUpdateTime(date);
                    audit.setFlowType(1);
                    audit.setFlowName(Immutable.DEL_ACCIDENT_BULLETIN);
                    audit.setOperation(2);
                    audit.setTarget(AccidentBulletinServiceImpl.class.getName());
                    audit.setTitle("删除事故快报：" + entity.getName());
                    audit.setCorpCode(entity.getCorpCode());
                    audit.setBusinessIds(entity.getId());
                    audit.setInitiatorCode(entity.getUpdateUser());
                    audit.setDescription(entity.getName() + "");
                    audit.setState(1);
                    audit.setTemplateKey(accidentBulletin);
                    audit.setSetCode("institution_manage");
                    audit.setInitiatorAccount(user.getUserid());
                    audit.setId(DefaultIdGenerator.getInstance().generateLongId());
                    Map<String, Object> businessMap = new HashMap<>();
                    businessMap.put("approver", approver);
                    if (!flowManagement.initFlow(user, audit, businessMap)) {
                        factory.close(false);
                        msg.setCode(BusinessCode.FAILURE.getCode());
                        msg.setDescription("提交失败，原因是无法启动流程");
                        return msg;
                    }
                }
                msg.setCode(BusinessCode.SUCCESS.getCode());
                msg.setDescription("事故快报删除成功");
                msg.setData(value);
                return msg;
            } else {
                msg.setCode(BusinessCode.FAILURE.getCode());
                msg.setDescription("事故快报删除失败");
                msg.setData(value);
                return msg;
            }
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
            return msg;
        }
    }

    @Override
    public MessageBean<AccidentBulletin> queryOne(String id) {
        MessageBean<AccidentBulletin> msg = new MessageBean<>();
        try (SessionFactory factory = new SessionFactory()) {
            if (StringUtils.isEmpty(id)) {
                msg.setCode(BusinessCode.EXCEPTION.getCode());
                msg.setDescription(BusinessCode.EXCEPTION.getDescription());
                return msg;
            }
            AccidentBulletin accidentBulletin = factory.getMapper(AccidentBulletinMapper.class).queryOne(id);
            setNames(accidentBulletin);
            msg.setData(accidentBulletin);
            msg.setCode(BusinessCode.SUCCESS.getCode());
            msg.setDescription("查询事故快报详情成功");
            return msg;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
            return msg;
        }
    }

    @Override
    public MessageBean<DataBean<AccidentBulletin>> queryByContion(String corpCode, String name, String departmentCode, String accidentType, Integer start, Integer rows) {
        MessageBean<DataBean<AccidentBulletin>> msg = new MessageBean<>();
        try (SessionFactory factory = new SessionFactory()) {
            List<AccidentBulletin> list = factory.getMapper(AccidentBulletinMapper.class).queryByCondition(corpCode, name, departmentCode,
                    accidentType, null, null, start, rows);
            Integer totalNumber = factory.getMapper(AccidentBulletinMapper.class).countByCondition(corpCode, name, departmentCode, accidentType, null, null);
            rows = rows == null ? totalNumber : (rows <= 0 ? 1 : rows);
            Integer totalPage = (totalNumber > rows) ? (totalNumber % rows == 0 ? totalNumber / rows : totalNumber / rows + 1) : 1;
            DataBean<AccidentBulletin> dataBean = new DataBean<>();
            list.forEach(item -> setNames(item));
            dataBean.setList(list);
            dataBean.setTotalNumber(totalNumber);
            dataBean.setTotalPage(totalPage);
            dataBean.setPageSize(rows);
            msg.setCode(BusinessCode.SUCCESS.getCode());
            msg.setDescription("查询事故快报列表成功");
            msg.setData(dataBean);
            return msg;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
            return msg;
        }
    }

    @Override
    public MessageBean<List<AccidentBulletin>> queryAll(String corpCode) {
        MessageBean<List<AccidentBulletin>> msg = new MessageBean<>();
        try (SessionFactory factory = new SessionFactory()) {
            List<AccidentBulletin> list = factory.getMapper(AccidentBulletinMapper.class).queryByCondition(corpCode, null, null,
                    null, null, null, null, null);
            msg.setDescription("查询事故快报列表成功");
            list.forEach(item -> setNames(item));
            msg.setData(list);
            return msg;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
            return msg;
        }
    }

    @Override
    public List<AccidentBulletin> exportList(StaffBean user, String corpCode, String name, String departmentCode, String accidentType) {
        try (SessionFactory factory = new SessionFactory()) {
            List<AccidentBulletin> list = factory.getMapper(AccidentBulletinMapper.class).queryByCondition(corpCode, name, departmentCode,
                    accidentType, null, null, null, null);
            if (null != list && list.size() > 0) {
                Map<String, DictData> cacheMap = dataService.getCacheMap();
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                list.forEach(bean -> {
                    if (StringUtils.isNotEmpty(bean.getAccidentType())) {
                        DictData element = cacheMap.get(bean.getAccidentType());
                        bean.setAccidentTypeName(element == null ? null : element.getDictLabel());
                    }
                    if (null != bean.getOccurrenceTime()) {
                        bean.setOccurrenceTimeStr(sdf.format(bean.getOccurrenceTime()));
                    }
                });
            }
            return list;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            return null;
        }

    }

    private void setNames(AccidentBulletin bean) {
        if (bean != null) {
            Map<String, DictData> cacheMap = dataService.getCacheMap();
            if (StringUtils.isNotEmpty(bean.getAccidentType())) {
                DictData element = cacheMap.get(bean.getAccidentType());
                bean.setAccidentTypeName(element == null ? null : element.getDictLabel());
            }
        }
    }

    @Override
    public void editApproval(Audit audit) {
        SessionFactory factory = null;
        try {
            factory = new SessionFactory();
            AccidentBulletin entity = factory.getMapper(AccidentBulletinMapper.class).queryOne(audit.getBusinessIds());
            if (null != entity) {
                entity.setStatus(1);
                factory.getMapper(AccidentBulletinMapper.class).update(entity);
                //发送短信或者邮件或者代办信息
                //要做相应的推送操作，推送待办、邮件、短信
                SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                if (entity.getIsSendEmail() == 1) {
                    //要发送邮件
                    String text = formatter.format(entity.getOccurrenceTime()) + "," + entity.getOccurrencePlace() + entity.getDepartmentName() + "发生了一起事故，事故名称为：" +
                            entity.getName() + "事故起因为：" + entity.getAccidentReason();
                    List<String> codes = JSONObject.parseArray(entity.getSendEmailPerson(), String.class);
                    List<String> emailList = new ArrayList<>();
                    for (String code : codes) {
                        List<StaffBean> staffBeanList = (List<StaffBean>) util.staff(code, null).getData();
                        if (null != staffBeanList && staffBeanList.size() > 0) {
                            if (StringUtils.isNotEmpty(staffBeanList.get(0).getEmail()))
                                emailList.add(staffBeanList.get(0).getEmail());
                        }
                    }
//                        emailList.add("1527563570@qq.com");
                    //List<String> emails= JSONObject.parseArray(entity.getSendEmailPerson(),String.class);
                    //去发送邮件
                    if (null != emailList && emailList.size() > 0) {
                        SendEmail.complexMailSend(emailList, text, "事件快报通知：" + entity.getName(), null, null);
                    }
                }
                if (entity.getIsDeal() == 1) {
                    //发送待办，待办变成发送消息
                    List<Message> messageList = new ArrayList<>();
                    List<String> receiverCodes = JSONObject.parseArray(entity.getDealPerson(), String.class);
                    String text = entity.getOccurrencePlace() + entity.getDepartmentName() + "发生了一起事故，事故名称为：" +
                            entity.getName() + "事故起因为：" + entity.getAccidentReason();
                    for (String receiver : receiverCodes) {
                        Message message = new Message();
                        message.setId(DefaultIdGenerator.getInstance().generateLongId());
                        message.setAddTime(entity.getUpdateTime());
                        message.setIsRemove(0);
                        message.setIsRead(0);
                        message.setAddUser(entity.getUpdateUser());
                        message.setUpdateUser(entity.getUpdateUser());
                        message.setUpdateTime(entity.getUpdateTime());
                        message.setTitle("您有一项新的事故快报待查收");
                        message.setContent(text);
                        message.setReceiverCode(receiver);
                        messageList.add(message);
                    }
                    if (null != messageList && messageList.size() > 0) {
                        factory.getMapper(MessageMapper.class).batchInsert(messageList);
                    }
                }
                if (entity.getIsSendMsg() == 1) {
                    //发送短信
                    //根据从组织架构选择的人的code,发送短信
                    StringBuilder noMobiles = new StringBuilder();
                    int count = 0;
                    List<String> codes = JSONObject.parseArray(entity.getMsgPerson(), String.class);
                    List<String> phones = new ArrayList<>();
                    for (String code : codes) {
                        List<StaffBean> staffBeanList = (List<StaffBean>) util.staff(code, null).getData();
                        if (null != staffBeanList && staffBeanList.size() > 0) {
                            StaffBean user1 = staffBeanList.get(0);
                            if (StringUtils.isNotEmpty(user1.getMobile())) {
                                SendMsg.sendSMS(user1.getMobile(), entity.getMsgContent());
                            } else {
                                //SendMsg.sendSMS("18664933207",bean.getMsgContent());
                                noMobiles.append(user1.getName());
                                count++;
                            }
                        }
                    }
                }
            }
            factory.close();
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            if (null != factory)
                factory.close(false);
        }
    }

    @Override
    public void discardApproval(Audit audit) {
        SessionFactory factory = null;
        try {
            factory = new SessionFactory();
            AccidentBulletin entity = factory.getMapper(AccidentBulletinMapper.class).queryOne(audit.getBusinessIds());
            if (null != entity) {
                entity.setStatus(1);
                entity.setIsRemove(1);
                factory.getMapper(AccidentBulletinMapper.class).update(entity);
            }
            factory.close();
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            if (null != factory)
                factory.close(false);
        }
    }

    @Override
    public void processDiscard(Audit audit) {
        SessionFactory factory = null;
        try {
            factory = new SessionFactory();
            AccidentBulletin entity = factory.getMapper(AccidentBulletinMapper.class).queryOne(audit.getBusinessIds());
            if (null != entity) {
                if (Immutable.ACCIDENT_BULLETIN.equals(audit.getFlowName())) {
                    //保存事件
                    if (entity.getAddTime().compareTo(entity.getUpdateTime()) == 0) {
                        //新增流程被废弃
                        entity.setStatus(2);
                    } else {
                        //修改流程被废弃
                        entity.setStatus(3);
                    }
                }
                if (Immutable.DEL_ACCIDENT_BULLETIN.equals(audit.getFlowName())) {
                    //删除流程被废弃
                    entity.setStatus(4);
                }
                factory.getMapper(AccidentBulletinMapper.class).update(entity);
            }
            factory.close();
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            if (null != factory)
                factory.close(false);
        }
    }

    @Override
    public void reject(Audit audit, List<String> userIdList) {
        // TODO 流程驳回操作
    }

    @Override
    public void passApproval(Integer operation, Audit audit) {
        // TODO 流程提交成功操作
    }

    @Override
    public void afterPropertiesSet() {
        Map map = flowManagement.getHandlers();
        map.put(AccidentBulletinServiceImpl.class.getName(), this);
    }
}
